package com.young.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {
    private static final Integer MAX_QUEUE_CAPACITY=200;
    private static final Integer MAX_ALIVE_TIME=60;
    @Bean("myExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
        //设置线程池参数信息
        taskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors()+1);
        taskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2);
        taskExecutor.setQueueCapacity(MAX_QUEUE_CAPACITY);
        taskExecutor.setKeepAliveSeconds(MAX_ALIVE_TIME);
        taskExecutor.setThreadNamePrefix("myExecutor--");
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中任务的等待时间，如果超过这个时间还没有销毁就强制销毁
        taskExecutor.setAwaitTerminationSeconds(60);
        //修改拒绝策略为使用当前线程执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化线程池
        taskExecutor.initialize();
        return taskExecutor;
    }
}
